<script setup>
import {inject, onMounted, ref} from "vue";
import {doDelete, doGet, doPost} from "../http/httpRequest.js";
import {confirmMessage, showMessage} from "../util/utils.js";
import {useRoute, useRouter} from "vue-router";

//定义router对象，该对象中提供了一些路由方法供我们使用，比如router.push(), router.go()
let router = useRouter();
//定义route对象，该对象提供了一些路由属性/字段供我们使用，比如route.path;  route.params; 等等
let route = useRoute();

//定义线索列表对象，初始值是空
let clueList = ref([{
  ownerDO : {},
  activityDO : {},
  intentionStateDO : {},
  intentionProductDO : {},
  stateDO : {},
  sourceDO : {}
}])
//分页时总共有多少条数据
let total = ref(0)
//分页时每页显示多少条数据
let pageSize = ref(0)

//定义线索id的数组，这里定义的不是响应式的数组，因为该数组不需要在html页面上进行响应式显示
let clueIdArr = [];

//勾选或取消checkbox时会执行该函数
const handleSelectionChange = (newSelection) => {
  clueIdArr = [];
  newSelection.forEach(item => {
    let id = item.id;
    clueIdArr.push(id);
  })
}

//分页查询线索列表函数
const loadClueByPage = (current) => {
  doGet('/api/clues', {
    current : current //前面的current是参数名，后面的current是参数值
  }).then(resp => {
    if (resp.data.code === 200) {
      clueList.value = resp.data.data.list;
      total.value = resp.data.data.total;
      pageSize.value = resp.data.data.pageSize;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//分页函数
const toPage = (value) => {
  loadClueByPage(value);
}

//页面dom元素渲染后会触发执行
onMounted(() => {
  //分页查询线索列表数据
  loadClueByPage(1);
})

//导入线索Excel的蒙版弹层对话框是否显示，false不显示，true显示
let importExcelVisible = ref(false)
//导入线索(Excel)函数
const importExcel = () => {
  //弹一个窗
  importExcelVisible.value = true;
}

//定义上传组件el-upload的ref属性对象
let uploadRef = ref();

//导入Excel函数
const importExcelSubmit = () => {
  uploadRef.value.submit()
}

//注入flush这个key所对应的函数
let flushPage = inject('flush');
const uploadExcel = (options) => {
  //options是element-plus帮我注入的，（有点像spring的参数注入）
  console.log("options :  " , options);
  let uri = options.action;  // /api/importExcel
  let fileObj = options.file;

  let formData = new FormData();
  //把文件对象数据放入formData中，作为后续提交的数据
  formData.append('excelFile', fileObj);
  //实现文件的上传
  doPost(uri, formData).then(resp => {
    if (resp.data.code === 200) {
      showMessage('Excel导入成功', 'success');
      //页面做局部刷新
      flushPage();
    } else {
      showMessage('Excel导入失败，原因：' + resp.data.msg, 'error');
    }
  })
}

//录入线索
const add = () => {
  router.push('/dashboard/clue/add')
}

//编辑线索
const edit = (id) => {
  router.push('/dashboard/clue/edit/' + id)
}

//根据id删除线索
const del = (id) => {
  //删除前，让用户确认一下
  confirmMessage('您确定要删除此数据吗？').then(() => { //点确定就触发then函数
    doDelete('/api/clue/' + id, {}).then(resp => {
      if (resp.data.code === 200) {
        showMessage('删除成功', 'success')
        //局部刷新
        flushPage();
      } else {
        showMessage('删除失败，原因：' + resp.data.msg, 'error')
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消删除', 'warning')
  })
}

//批量删除线索
const batchDel = () => {
  //判断用户有没有选择数据，没有选数据，提示他选择要删除的数据
  if (clueIdArr.length <= 0) {
    showMessage('请选择要删除的数据', 'warning');
    return;
  }
  confirmMessage('您确定要删除这些数据吗？').then(() => { //点确定就触发then函数
    //发送请求，批量删除
    let ids = clueIdArr.join(','); // 数组[1,3,5,6,8,12]  ==> ids = "1,3,5,6,8,12";
    doDelete('/api/clue', {
      ids : ids
    }).then(resp => {
      if (resp.data.code === 200) {
        showMessage('批量删除成功', 'success');
        //局部刷新
        flushPage();
      } else {
        showMessage('批量删除失败，原因：' + resp.data.msg, 'error');
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消批量删除', 'warning')
  })
}

//查看详情
const view = (id) => {
  router.push('/dashboard/clue/detail/' + id)
}
</script>

<template>
  <el-button type="primary" @click="add">录入线索</el-button>
  <el-button type="success" @click="importExcel">导入线索(Excel)</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>

  <el-table
      :data="clueList"
      style="width: 100%"
      @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50"/>
    <el-table-column type="index" label="序号" width="65"/>
    <el-table-column property="ownerDO.name" label="负责人" width="120" />
    <el-table-column property="activityDO.name" label="所属活动"/>
    <el-table-column label="姓名">
      <template #default="scope">
        <a href="javascript:void(0)" @click="view(scope.row.id)">{{ scope.row.fullName }}</a>
      </template>
    </el-table-column>
    <el-table-column property="phone" label="手机" width="120"/>
    <el-table-column property="weixin" label="微信" width="120"/>
    <el-table-column property="intentionStateDO.typeValue" label="意向状态"/>
    <el-table-column property="intentionProductDO.name" label="意向产品"/>
    <el-table-column property="stateDO.typeValue" label="线索状态"/>
    <el-table-column property="sourceDO.typeValue" label="线索来源"/>
    <el-table-column property="nextContactTime" label="下次联系时间" width="165"/>
    <el-table-column label="操作" width="230">
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination :background="true"
                 layout="prev, pager, next, jumper, ->, total"
                 :total="total"
                 :page-size="pageSize"
                 @current-change="toPage"/>

  <!-- 导入线索Excel的蒙版弹层对话框 -->
  <el-dialog v-model="importExcelVisible" title="导入线索(Excel)" width="700" center>
    <el-upload
        ref="uploadRef"
        action="/api/importExcel"
        :http-request="uploadExcel"
        :auto-upload="false">
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <span class="ml-3" >
        请选择要导入的Excel文件
      </span>
      <template #tip>
        <div class="el-upload__tip">
          重要提示：
          <ul>
            <li>上传仅支持后缀名为.xls或.xlsx的文件；</li>
            <li>给定Excel文件的第一行将视为字段名；</li>
            <li>请确认您的文件大小不超过50MB；</li>
            <li>日期值以文本形式保存，必须符合yyyy-MM-dd格式；</li>
            <li>日期时间以文本形式保存，必须符合yyyy-MM-dd HH:mm:ss的格式；</li>
          </ul>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="importExcelVisible = false">关 闭</el-button>
        <el-button type="primary" @click="importExcelSubmit">导 入</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>